<template>
  <div>
    <div class="bar">
      <div class="bar-header">
        <h2 class="title">
          {{ raceDetail.title }}
        </h2>
        <div class="btns">
          <n-button class="btn" size="small" round type="warning">
            <i class="iconfont icon-bisai"></i>
            <span class="text" v-for="(item, index) in formats" :key="item.value"
              v-show="raceDetail.format == item.value">{{ item.label }}</span>
          </n-button>
          <n-button v-for="(item, index) in auths" :key="item.value" class="btn" size="small" round :type="item.type"
            v-show="raceDetail.type == item.value">
            <i class="iconfont icon-tuandui"></i>{{ item.label }}
          </n-button>
        </div>
      </div>

      <div class="bar-date">
        <div class="date">开始时间：{{ raceDetail.startTime }}</div>
        <div class="date">结束时间：{{ raceDetail.endTime }}</div>
      </div>

      <div class="bar-bar">
        <n-progress class="progress" type="line" :height="20" :percentage="percentage" status="success"
          :indicator-placement="'inside'" processing />
      </div>

      <div class="box">
        <div class="time">
          <span class="countdown" style="font-variant-numeric: tabular-nums">
            <!--  -->
            <n-countdown :duration="getDuration" :active="active" />
            <!--  -->
          </span>
        </div>
        <div class="tips">
          <div class="tip">
            <n-button size="tiny" type="warning" strong secondary>
              <i class="iconfont icon-no-full"></i>&emsp13;
              {{
                raceDetail.allowEndEntry
                  ? "允许比赛后进入"
                  : "不允许比赛后进入"
              }}
            </n-button>
          </div>
          <div class="tip">
            <n-button size="tiny" type="info" strong secondary>
              <i class="iconfont icon-fenshu"></i>&emsp13;
              {{
                raceDetail.accountAwardType == 0
                  ? "无设置奖项"
                  : raceDetail.accountAwardType == 1
                    ? "设置占比获奖"
                    : "设置人数获奖"
              }}
            </n-button>
          </div>
          <div class="tip">
            <n-button size="tiny" type="success" strong secondary>
              <i class="iconfont icon-paiming"></i>&emsp13;
              {{ raceDetail.lockRank == 1 ? "不封榜" : "开启封榜" }}
            </n-button>
          </div>
        </div>
      </div>
    </div>

    <div class="race">
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="题目" name="problem">
          <template #label>
            <div @click="flashProblem">
              <i class="iconfont icon-tuanduishezhi"></i>题目
            </div>
          </template>
        </el-tab-pane>

        <el-tab-pane label="排名" name="rank" v-if="raceDetail.format !== 1 ||
          store.oj.userData.authLevel === 2 ||
          (store.oj.userData.id === raceDetail.uid &&
            store.oj.userData.authLevel !== 0)
        ">
          <template #label>
            <div>
              <i class="iconfont icon-paiming"></i>排名
            </div>
          </template>
        </el-tab-pane>
        <el-tab-pane label="评测" name="evaluation" v-if="raceDetail.format !== 1 ||
          store.oj.userData.authLevel === 2 ||
          (store.oj.userData.id === raceDetail.uid &&
            store.oj.userData.authLevel !== 0)
        ">
          <template #label>
            <div>
              <i class="iconfont icon-fenlei3"></i>评测
            </div>
          </template>
        </el-tab-pane>

        <el-tab-pane label="公告" name="notice">
          <template #label>
            <div><i class="iconfont icon-xiaoxi2"></i>公告</div>
          </template>
        </el-tab-pane>

      </el-tabs>

    </div>

    <div class="tabContain">
      <router-view :key="route.name" v-slot="{ Component }">
        <transition>
          <component :is="Component" :raceDetail="raceDetail" @lockRank="lockRank" />
        </transition>
      </router-view>
    </div>
  </div>
</template>

<script setup>
import useStore from "@/store"
import {
  onMounted,
  ref,
  reactive,
  onUnmounted,
  watch,
  computed
} from "vue"
import { getRaceDetailAPI } from "@/api/ojAPI/ojAPI"
import { useRoute, useRouter } from "vue-router"
import { formats, auths } from './config'

const route = useRoute()
const router = useRouter()
const active = ref(false)
const activeName = ref("problem")
const arr = ["problem", "evaluation", "notice", "rank", "closedList"]
watch(
  () => activeName.value,
  (newV) => {
    if (arr.includes(newV)) {
      router.push(`/home/racepage/${route.params.rid}/${newV}`)
    }
  }
)

watch(
  () => route,
  (newV) => {
    activeName.value = newV.name.slice(8)
  },
  { immediate: true }
)

const store = useStore()


onMounted(() => {
  getRaceDetail(route.params.rid)
  active.value = true
})
onUnmounted(() => {
  active.value = false
  clearInterval(timer.value)
})
//获取比赛详情
const raceDetail = reactive({
  allowEndEntry: false
})

const getRaceDetail = async (id) => {

  await getRaceDetailAPI(id)
    .then((res) => {
      if (res.data.code === 200) {
        Object.assign(raceDetail, res.data.data)
        sessionStorage.setItem(raceDetail.id, raceDetail.endTime)
        getpercentage()
        getpercentageTimer()
      }
    })
    .catch((err) => {
      console.log(err)
    })
}
let getDuration = computed(() => {
  if (raceDetail.endTime) {
    const now = Date.now()
    const endTime = new Date(raceDetail.endTime).getTime()
    return endTime - now
  }
  return 0
})

const percentage = ref(0)
const getpercentage = () => {
  const pre = raceDetail.startTime
  const end = raceDetail.endTime
  if (!pre || !end) {
    percentage.value = 0
    return
  }
  const startTime = new Date(pre).getTime()
  const endTime = new Date(end).getTime()
  const now = Date.now()
  if (now >= endTime) {
    percentage.value = 100
    return
  }
  if (now <= startTime) {
    percentage.value = 0
    return
  }
  const passed = Number(((now - startTime) / 1000).toFixed(0))
  const duration = Number(((endTime - startTime) / 1000).toFixed(0))
  percentage.value = parseFloat(
    (parseFloat(passed / duration) * 100).toFixed(2)
  )
  return
}
const timer = ref(null)
const getpercentageTimer = () => {
  if (timer.value) {
    clearInterval(timer.value)
  }
  timer.value = setInterval(() => {
    getpercentage()
  }, 10000)
}

const lockRank = () => {
  getRaceDetailAPI(route.params.rid)
    .then((res) => {
      if (res.data.code === 200) {
        Object.assign(raceDetail, res.data.data)
        sessionStorage.setItem(raceDetail.id, raceDetail.endTime)
        sessionStorage.setItem(`${raceDetail.id}Detail`, JSON.stringify(raceDetail))
        getpercentage()
        getpercentageTimer()
      }
    })
    .catch((err) => {
      console.log(err)
    })
}

</script>

<style lang="less" scoped>
.bar {
  user-select: none;
  width: 95%;
  padding-top: 10px;
  margin: 10px auto 20px auto;
  border-radius: 16px;
  background: #ffffff;
  padding: 10px;
  box-shadow: 5px 5px 16px #e6e6e6, -5px -5px 16px #ffffff;
  display: flex;
  flex-direction: column;
  height: 250px;

  .bar-header {
    display: flex;

    .title {
      margin: auto;
    }

    .btns {
      display: flex;
      margin: auto 0 auto auto;

      .btn {
        margin: auto 10px;
      }
    }
  }

  .bar-date {
    margin: 30px auto;
    display: flex;
    justify-content: space-between;
    height: 30px;
    line-height: 30px;
    width: 100%;

    .date {
      margin: auto 20px;
      font-size: 16px;
      color: #8c8c8c;
    }
  }

  .bar-bar {
    width: 90%;
    margin: 0 auto;

    .progress {
      width: 100%;
      margin: 0 auto;
    }
  }

  .box {
    display: flex;
    user-select: none;
    width: 90%;
    margin: auto;

    .time {
      height: 80px;
      width: 50%;
      display: flex;

      .countdown {
        font-size: 30px;
        font-weight: 550;
        padding: 10px 30px;
        border-radius: 10px;
        margin: auto 0;
        color: #555;
        background: linear-gradient(145deg, #e6e6e6, #ffffff);
        box-shadow: 5px 5px 19px #d9d9d9, -5px -5px 19px #ffffff;
      }
    }

    .tips {
      height: 80px;
      width: 50%;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      position: relative;
      left: 30px;

      .tip {
        display: flex;
        justify-content: right;
      }
    }
  }
}

.race {
  width: 95%;
  padding-top: 10px;
  margin: 0 auto;
  border-radius: 1vw 1vw 0 0;
  background: #ffffff;
  padding: 10px;
  display: flex;
  flex-direction: column;

  .r-head {
    display: flex;
    justify-content: space-between;
    align-content: center;
    border-bottom: 1px solid rgb(58, 159, 85);
    padding-bottom: 10px;

    .r-search {
      width: 30%;
      display: flex;
      align-items: center;

      .switch {
        width: 30%;
        margin-left: 10px;
        margin-right: 5px;
      }
    }

    .r-do {
      display: flex;

      .r-deploy {
        margin-right: 10px;

        .n-button {
          --n-height: 31px !important;
          --n-border-radius: 20px !important;
          --n-font-size: 12px !important;
        }

        .large-text {
          padding: 10px;
        }

        .showChart {
          margin-top: 10px;
        }
      }

      .r-flash {
        margin-right: 10px;
      }

      .flash {
        animation: loader 0.88s infinite cubic-bezier(0.3, 0.5, 0.7, 1);
      }

      @keyframes loader {
        0% {
          transform: rotate(0deg);
          filter: hue-rotate(360deg);
        }

        100% {
          transform: rotate(360deg);
          filter: hue-rotate(0deg);
        }
      }
    }
  }
}

.tabContain {
  width: 95%;
  padding-top: 10px;
  margin: 0 auto;
  border-bottom-left-radius: 1vw;
  border-bottom-right-radius: 1vw;
  background: #ffffff;
  padding: 10px;
  display: flex;
  flex-direction: column;
}

.v-enter-active,
.v-leave-active {
  transition: opacity 0.5s ease;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
}

::v-deep(.el-tabs__header) {
  margin-bottom: 0 !important;
}

::v-deep(.is-top) {
  margin-bottom: 0 !important;
}
</style>
